﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Objects.DataClasses;
using System.ComponentModel;

namespace Subscriptions
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private SalesManagerEntities _context = new SalesManagerEntities();
        private SalesManagerCodes _codesContext = new SalesManagerCodes();
        private CollectionViewSource _subscriptionsViewSource;
        private CollectionViewSource _carrierViewSource;
        private CollectionViewSource _subscriptionStepsViewSource;
        private int _ownerID = 11;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _subscriptionsViewSource = (CollectionViewSource)FindResource("Subscriptions");
            _subscriptionStepsViewSource = (CollectionViewSource)FindResource("SubscriptionSteps");
            _subscriptionsViewSource.Source = from c in _context.tblSubscription
                                                .Include("SubscriptionSteps.SubscriptionStepProducts.Product")
                                                .Include("SubscriptionProducts.Product")
                                              where c.OwnerID == _ownerID
                                              orderby c.Description
                                              select c;
            //_subscriptionsViewSource.View.CurrentChanged += new EventHandler(SubscriptionsView_CurrentChanged);
            //SetSubscriptionsStepsView();
            cmbSubscriptions_SelectionChanged(null, null);

            var carrierList = (from c in _codesContext.codeCarrier
                                        select new {c.CarrierCode, c.Description}).ToList();
            carrierList.Add( new { CarrierCode=(string)null, Description=(string)null } );
            _carrierViewSource = (CollectionViewSource)FindResource("Carriers");
            _carrierViewSource.Source = carrierList;
        }

        private void SetSubscriptionsStepsView()
        {
            if (_subscriptionsViewSource.View.CurrentItem != null)
            {
                _subscriptionStepsViewSource.Source = ((tblSubscription)_subscriptionsViewSource.View.CurrentItem).SubscriptionSteps.ToList();
                _subscriptionStepsViewSource.SortDescriptions.Add(new SortDescription("Delay", ListSortDirection.Ascending));
            }
            else
                _subscriptionStepsViewSource.Source = null;
        }

        private void SubscriptionsView_CurrentChanged(object sender, EventArgs e)
        {
            SetSubscriptionsStepsView();
        }

        private void btnNewSubscription_Click(object sender, RoutedEventArgs e)
        {
            DialogProductList dlg = new DialogProductList(_ownerID);
            if ((bool)dlg.ShowDialog())
            {
                //tblSubscription newSubscription = new tblSubscription();
                tblSubscription newSubscription = (tblSubscription)((IEditableCollectionView)_subscriptionsViewSource.View).AddNew();
                ((IEditableCollectionView)_carrierViewSource.View).CommitNew();
                newSubscription.Description = "New";
                newSubscription.SubscriptionCode = "aaa";
                //newSubscription.Product = (tblProduct)_context.GetObjectByKey(
                //    new System.Data.EntityKey("SalesManagerEntities.tblProduct", "ProductID", dlg.ProductID));
                _context.AddTotblSubscription(newSubscription);
                cmbSubscriptions.SelectedItem = newSubscription;
            }
        }

        private void cmbSubscriptions_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            tblSubscriptionStep[] steps = ((tblSubscription)_subscriptionsViewSource.View.CurrentItem).SubscriptionSteps.ToArray();

            if (steps.Length > 0)
            {
                tblSubscriptionStep step = steps.FirstOrDefault(c => c.PrevSubscriptionStep == null);
                step.StepOrder = 1;
                RecurseSetStepOrder(step.NextSteps, 2);
            }
            if (_subscriptionStepsViewSource.View != null) 
                _subscriptionStepsViewSource.View.Refresh();
        }

        private void RecurseSetStepOrder(EntityCollection<tblSubscriptionStep> steps, int level)
        {
            if (steps == null)
                return;
            foreach (tblSubscriptionStep step in steps)
            {
                step.StepOrder = level;
                RecurseSetStepOrder(step.NextSteps, level + 1);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            _context.SaveChanges();
        }

        private void btnAddStep_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionStep newStep = (tblSubscriptionStep)((IEditableCollectionView)_subscriptionStepsViewSource.View).AddNew();
            ((IEditableCollectionView)_subscriptionStepsViewSource.View).CommitNew();
            newStep.Delay = 0;
            newStep.RecurrenceCount = 0;
            newStep.RecurrenceTerm = 0;

            tblSubscription subscription = (tblSubscription)_subscriptionsViewSource.View.CurrentItem;
            tblSubscriptionStep step = subscription.SubscriptionSteps.FirstOrDefault(c=>c.PrevSubscriptionStep == null);
            if (step != null)
                while (step.NextSteps.Count > 0)
                    step = step.NextSteps.First();
            newStep.PrevSubscriptionStep = step;

            lbSubscriptionSteps.SelectedItem = newStep;
        }

        private void btnMoveUp_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionStep subscriptionStep = (tblSubscriptionStep)((Button)e.Source).CommandParameter;
            tblSubscriptionStep prevStep = subscriptionStep.PrevSubscriptionStep;

            if (prevStep != null)
            {
                subscriptionStep.PrevSubscriptionStep = prevStep.PrevSubscriptionStep;
                subscriptionStep.StepOrder--;
                prevStep.PrevSubscriptionStep = subscriptionStep;
                prevStep.StepOrder++;
            }
            _subscriptionStepsViewSource.View.Refresh();
        }

        private void btnMoveDown_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionStep subscriptionStep = (tblSubscriptionStep)((Button)e.Source).CommandParameter;
            tblSubscriptionStep nextStep = subscriptionStep.NextSteps.FirstOrDefault();

            if (nextStep != null)
            {
                nextStep.PrevSubscriptionStep = subscriptionStep.PrevSubscriptionStep;
                nextStep.StepOrder--;
                subscriptionStep.PrevSubscriptionStep = nextStep;
                subscriptionStep.StepOrder++;
            }
            _subscriptionStepsViewSource.View.Refresh();
        }

        private void btnAddProduct_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionStep subscriptionStep = (tblSubscriptionStep)((Button)e.Source).CommandParameter;
            DialogProductList dlg = new DialogProductList(_ownerID);
            if ((bool)dlg.ShowDialog())
            {
                tblSubscriptionStepProduct newProduct = new tblSubscriptionStepProduct();
                newProduct.Product = (tblProduct)_context.GetObjectByKey(
                    new System.Data.EntityKey("SalesManagerEntities.tblProduct", "ProductID", dlg.ProductID));
                newProduct.SubscriptionStep = subscriptionStep;
                newProduct.Qty = 1;
                newProduct.Price = null;
            }
        }

        private void btnDeletePRoduct_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionStepProduct subscriptionStepProduct = (tblSubscriptionStepProduct)((Button)e.Source).CommandParameter;
            _context.DeleteObject(subscriptionStepProduct);
        }

        private void btnDeleteTriggerProduct_Click(object sender, RoutedEventArgs e)
        {
            tblSubscription subscription = (tblSubscription)((Button)e.Source).CommandParameter;
            DialogProductList dlg = new DialogProductList(_ownerID);
            if ((bool)dlg.ShowDialog())
            {
                tblSubscriptionProduct newProduct = new tblSubscriptionProduct();
                newProduct.Product = (tblProduct)_context.GetObjectByKey(
                    new System.Data.EntityKey("SalesManagerEntities.tblProduct", "ProductID", dlg.ProductID));
                newProduct.Subscription = subscription;
            }
        }

        private void btnAddSubscriptionProduct_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionProduct subscriptionProduct = (tblSubscriptionProduct)((Button)e.Source).CommandParameter;
            _context.DeleteObject(subscriptionProduct);
        }

        private void btnRemoveStep_Click(object sender, RoutedEventArgs e)
        {
            tblSubscriptionStep subscriptionStep = (tblSubscriptionStep)((Button)e.Source).CommandParameter;
            tblSubscriptionStep nextStep = subscriptionStep.NextSteps.First();

            if (nextStep != null)
            {
                nextStep.PrevSubscriptionStep = subscriptionStep.PrevSubscriptionStep;
                nextStep.StepOrder--;
            }
            _context.DeleteObject(subscriptionStep);
        }
    }
}
